﻿@using Microsoft.AspNetCore.Mvc.Localization;
@inject IViewLocalizer Localizer
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />

    <link href="~/webuploader/webuploader.css" rel="stylesheet" />
    <link href="~/lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/webuploader/webuploader.js"></script>
    <script>
        jQuery(function () {
            var $ = jQuery,
                $list = $('#thelist'),
                $btn = $('#ctlBtn'),
                state = 'pending',
                fileMd5,
                flag = true,
                dataState,
                fm = [],
                fnum,
                Token,
                uploader;
            var FileExt = ["gif", "jpg", "jpeg", "png", "bmp", "mpg", "mpeg", "mp4", "avi", "docx", "xlsx", "pdf", "pptx"];
            Token = 'xxxhiaoweriaeb';
            if (Token == '' || Token == 'undefined') {
                $("#uploader").hide();
                alert("登录超时，请重新登录。");
            }
            //监听分块上传过程中的三个时间点
            WebUploader.Uploader.register({
                "before-send-file": "beforeSendFile",
                "before-send": "beforeSend",
                "after-send-file": "afterSendFile",
            }, {
                beforeSendFile: function (file) {
                    var startTime = new Date(file.lastModifiedDate);
                    fileName = file.name;
                    var deferred = WebUploader.Deferred();
                    (new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024)
                        .progress(function (percentage) {
                            console.log("正在读取文件");
                        })
                        .then(function (val) {
                            fileMd5 = val;
                            fm.push(fileMd5);
                            deferred.resolve();
                        });
                    return deferred.promise();
                },
                //时间点2：如果有分块上传，则每个分块上传之前调用此函数
                beforeSend: function (block) {
                    var deferred = WebUploader.Deferred();

                    //上传前ajax检测一下此文件块是否已经上传

                    this.owner.options.formData.fileMd5 = fileMd5;
                    this.owner.options.formData.chunk = block.chunk;
                    deferred.resolve();
                    return deferred.promise();
                },
                //时间点3：所有分块上传成功后调用此函数
                afterSendFile: function (file) {
                    var deferred = $.Deferred();
                    $('#' + file.id).find('p.state').text('执行最后一步');
                    console.log(file);
                    console.log(file.guid);
                    $.ajax({
                        type: "POST",
                        url: "/Assets/FileMerge",
                        data: {
                            guid: file.guid,
                            fileMd5: fm[fnum],
                            fileName: file.name
                        },
                        cache: false,
                        async: false,
                        success: function (response) {
                            fnum++;
                            console.log(response);
                            if (response.success == true) {
                                dataState = response;
                                flag = true;
                            } else {
                                flag = false;
                            }
                            deferred.resolve();
                        },
                        error: function () {
                            fnum++;
                            dataState = undefined;
                            flag = false;
                            deferred.reject();
                        }
                    });

                    return deferred.promise();
                }
            });
            uploader = WebUploader.create({
                resize: false,
                fileNumLimit: 10,
                swf: '/js/Uploader.swf',
                server: '/Assets/FileSave',
                pick: '#picker',
                chunked: true,
                chunkSize: 10 * 1024 * 1024,
                chunkRetry: 5
                //, formData: {
                //    guid: GUID
                //}
            });
            uploader.on('beforeFileQueued', function (file) {
                var isAdd = false;
                for (var i = 0; i < FileExt.length; i++) {
                    if (file.ext == FileExt[i]) {
                        file.guid = WebUploader.Base.guid();
                        isAdd = true;
                        break;
                    }
                }
                return isAdd;
            });
            uploader.on('uploadBeforeSend', function (object, data, headers) {
                //console.log(object);
                headers.Authorization = Token;
                data.guid = object.file.guid;
            });

            var demoListView = $('#demoList');
            // 当有文件添加进来的时候
            uploader.on('fileQueued', function (file) {
                var tr = $(['<tr id="' + file.id + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td><p class="state">@Localizer["Wait"]...</p></td>'
                    , '<td>'
                    , '<div class="progress progress-striped active">'
                    , '<div class="progress-bar" role="progressbar" style="width: 0%" >'
                    , '</div>'
                    , '</div>'
                    , '</td>'
                    , '</tr>'].join(''));
                demoListView.append(tr);

                @*$list.append('<div id="' + file.id + '" class="item">' +
                    '<h4 class="info">' + file.name + '</h4>' +
                    '<input type="hidden" id="h_' + file.id + '" value="' + file.guid + '" />' +
                    '<p class="state">@Localizer["Wait"]...</p>' +
                    '</div>');*@
            });



            // 文件上传过程中创建进度条实时显示。
            uploader.on('uploadProgress', function (file, percentage) {
                var $li = $('#' + file.id),
                    $percent = $li.find('.progress .progress-bar');
                // 避免重复创建
                if (!$percent.length) {
                    $percent = $('<div class="progress progress-striped active">' +
                        '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                        '</div>' +
                        '</div>').appendTo($li).find('.progress-bar');
                }
                $li.find('p.state').text('上传中');

                $percent.css('width', percentage * 100 + '%');
            });

            uploader.on('uploadSuccess', function (file) {
                if (dataState == undefined) {
                    $('#' + file.id).find('p.state').text('@Localizer["FailUpload"]');
                    $('#' + file.id).find('button').remove();
                    $('#' + file.id).find('p.state').before('<button id="retry" type="button" class="btn btn-primary fright retry pbtn">重新上传</button>');
                    flag = false;
                    file.setStatus('error');
                }
                if (dataState.success == true) {
                    $('#' + file.id).find('p.state').text('@Localizer["Success"]');
                    $('#' + file.id).find('button').remove();

                } else {
                    $('#' + file.id).find('p.state').text('@Localizer["FailUpload"]');
                    flag = false;
                }
            });

            uploader.on('uploadError', function (file) {
                $('#' + file.id).find('p.state').text('@Localizer["FailUpload"]');
            });

            uploader.on('uploadComplete', function (file) {
                $('#' + file.id).find('.progress').fadeOut();
            });

            uploader.on('all', function (type) {
                if (type === 'startUpload') {
                    state = 'uploading';
                } else if (type === 'stopUpload') {
                    state = 'paused';
                } else if (type === 'uploadFinished') {
                    state = 'done';
                }
                if (state === 'done') {
                    $btn.text('@Localizer["Continue"]');
                } else if (state === 'uploading') {
                    $btn.text('@Localizer["Pause"]');
                } else {
                    $btn.text('@Localizer["Start"]');
                }
            });
            $btn.on('click', function () {
                if (state === 'uploading') {
                    uploader.stop();
                } else if (state == 'done') {
                    window.location.reload();
                }
                else {
                    uploader.upload();
                }
            });
        });
    </script>
</head>
<body>
    <div id="uploader" class="wu-example">
        @*<span style="color:red">
                @Localizer["Support"] gif,jpg,jpeg,png,bmp,mpg,mpeg,mp4,avi,docx,xlsx,pdf,pptx @Localizer["FileFormat"]
            </span>*@
        <div class="btns">
            <blockquote class="layui-elem-quote quoteBox">
                <div class="layui-inline">
                    <div id="picker" class="webuploader-container">
                        <div>@Localizer["Choose"]</div>
                        <input type="file" name="file" class="webuploader-element-invisible" multiple="multiple">
                    </div>
                </div>
                <div class="layui-inline">
                    <button id="ctlBtn" class="btn btn-default btn-large"><div>@Localizer["Start"]</div></button>
                </div>
            </blockquote>
        </div>
        <div id="thelist" class="uploader-list"></div>
        <div class="layui-upload-list">
            <table class="layui-table">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>状态</th>
                        <th>进度</th>
                    </tr>
                </thead>
                <tbody id="demoList"></tbody>
            </table>
        </div>
    </div>
</body>
</html>